<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      title="查看编辑围栏"
      top="65px"
      :width="1200"
      destroy-on-close
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      append-to-body
      @open="handleOpenDialog()"
      @close="handleCloseDialog()"
    >
      <div class="flex dialog-container">
        <div class="left" :class="{ 'fold-inner-left': !sideOpened }">
          <el-form ref="formRef" :model="fenceInfo" label-position="right" label-width="100px">
            <div class="portion">
              <el-form-item label="搜索地址:" style="margin-bottom: 0px">
                <div class="flex flex-1">
                  <el-autocomplete
                    v-model="markerSearchValue"
                    :trigger-on-focus="false"
                    :teleported="false"
                    clearable
                    placeholder="请输入地址"
                    :fetch-suggestions="handleSearch"
                    @select="handleSelect"
                  >
                    <template #append>
                      <el-button>
                        <template #icon><ep-Search /></template>
                      </el-button>
                    </template>
                  </el-autocomplete>
                </div>
              </el-form-item>
            </div>

            <el-divider />
            <div class="portion">
              <div class="title">{{ titleType }}围栏</div>
              <el-form-item label="围栏类型:" required prop="railType">
                <el-radio-group v-model="fenceInfo.railType" :disabled="viewOrEditStatus !== 0" @change="handleChangeType">
                  <el-tooltip
                    placement="top"
                    raw-content
                    content="1.画圆/矩形：鼠标左键点击，拖动鼠标，松开左键，完成画圆/矩形。</br>2.画多边形：左键点击，移动鼠标，再次点击，依次类推，双击左键，完成画多边形。"
                  >
                    <el-radio-button label="自定义" :value="0" />
                  </el-tooltip>
                  <el-tooltip
                    placement="top"
                    raw-content
                    content="目前已支持行政区域围栏的绘制，由于行政划分最快三个月会更新一次，行政区域围栏会存在一定滞后性。"
                  >
                    <el-radio-button label="行政区域" :value="1" />
                  </el-tooltip>
                </el-radio-group>
              </el-form-item>
              <el-form-item
                v-if="fenceInfo.railType === 0"
                label="地址:"
                prop="address"
                :rules="[{ required: true, message: '围栏地址不能为空' }]"
              >
                <el-input
                  v-model="fenceInfo.address"
                  placeholder="请输入围栏地址"
                  :maxlength="50"
                  :disabled="viewOrEditStatus === 1"
                ></el-input>
              </el-form-item>
              <el-form-item
                v-if="fenceInfo.railType === 1"
                label="地址:"
                prop="codes"
                :rules="[{ required: true, message: '围栏地址不能为空' }]"
              >
                <el-cascader
                  v-if="!fenceInfo.id"
                  ref="cascaderRef"
                  v-model="fenceInfo.codes"
                  :options="purchaseAreaTree"
                  :props="{ value: 'code', label: 'name', multiple: true, checkStrictly: true }"
                  placeholder="请选择省、市、县区"
                  collapse-tags
                  collapse-tags-tooltip
                  clearable
                  style="width: 100%"
                  @change="changeDistrictCode"
                ></el-cascader>
                <el-input v-if="fenceInfo.id" v-model="fenceInfo.codes" disabled></el-input>
              </el-form-item>
              <div class="flex justify-center">
                <el-button size="default" type="primary" :disabled="viewOrEditStatus === 1" :loading="submitLoading" @click="handleAddRail">
                  确定
                </el-button>
                <el-button size="default" @click="handleCancelRail">取 消</el-button>
              </div>
            </div>
            <el-divider />
          </el-form>

          <div class="portion" style="flex: 1; overflow-y: hidden">
            <div class="title flex-x-b">
              围栏列表
              <div class="flex">
                <el-input v-model="searchKey" placeholder="请输入关键字查询" clearable>
                  <template #append>
                    <el-button @click="fetchRailList">
                      <template #icon><ep-Search /></template>
                    </el-button>
                  </template>
                </el-input>
              </div>
            </div>
            <el-table
              v-loading="tableLoading"
              class="fit-table margin-top-sm"
              border
              stripe
              :row-class-name="tableRowClassName"
              table-layout="auto"
              height="calc(100% - 20px)"
              :data="tableData"
            >
              <el-table-column label="操作" align="center" width="175">
                <template #default="{ row }">
                  <el-button type="primary" size="small" link @click="handleViewOrEdit(row)">
                    查看{{ row.railType === 0 ? '编辑' : '详情' }}
                  </el-button>
                  <el-button type="primary" size="small" class="!ml-5" link @click="handleRailUpdateStatus(row)">更改状态</el-button>
                  <el-button type="danger" size="small" class="!ml-5" link @click="handleDeleteRail(row.id)">删除</el-button>
                </template>
              </el-table-column>
              <el-table-column label="地址" prop="address" align="center" min-width="200" />
              <el-table-column label="围栏状态" prop="railStatus" align="center" width="90">
                <template #default="{ row }">
                  <el-tag :type="row.railStatus === railStatusOptions[0].value ? 'success' : 'info'">
                    {{ railStatusOptions.find(item => item.value === row.railStatus)?.label }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="围栏类型" prop="railType" align="center" width="90">
                <template #default="{ row }">
                  <span>{{ railTypeOptions.find(item => item.value === row.railType)?.label }}</span>
                </template>
              </el-table-column>
              <el-table-column label="围栏半径[米]" prop="radius" align="center" width="110" />
              <el-table-column label="更新人" prop="updateBy" align="center" width="80" />
              <el-table-column label="更新时间" prop="updateTime" align="center" width="160" />
              <el-table-column label="创建人" prop="createBy" align="center" width="80" />
              <el-table-column label="创建时间" prop="createTime" align="center" width="160" />
            </el-table>
          </div>
        </div>
        <div class="flex-1 right">
          <div id="map-container"></div>
          <div v-show="fenceInfo.railType === 0 && viewOrEditStatus === 0" class="toolbar-container">
            <el-tooltip placement="left" raw-content content="画圆">
              <div class="toolbar-item" @click="handleDraw(ShapeTypeEnum.Circle)">
                <img :src="circle_icon" />
              </div>
            </el-tooltip>
            <el-tooltip placement="left" raw-content content="画矩形">
              <div class="toolbar-item" @click="handleDraw(ShapeTypeEnum.Rectangle)">
                <img :src="rectangle_icon" />
              </div>
            </el-tooltip>
            <el-tooltip placement="left" raw-content content="画多边形">
              <div class="toolbar-item" @click="handleDraw(ShapeTypeEnum.Polygon)">
                <img :src="polygon_icon" />
              </div>
            </el-tooltip>
          </div>
          <div class="hamburger-container" @click="sideOpened = !sideOpened">
            <el-icon color="#777C90" size="14px" class="fold-inner" :class="{ 'fold-inner-rotate': !sideOpened }">
              <ep-ArrowLeftBold />
            </el-icon>
          </div>
        </div>
      </div>

      <div class="hidden">
        <!-- marker点带关闭按钮 -->
        <Marker ref="markerRef" @close="clearMarker" />
        <RailInfoWindow
          ref="railInfoWindowRef"
          :rail-info="railInfo"
          :allow-edit="allowEdit"
          @edit-overlay="editOverlay"
          @close="handleCloseInfoWindow"
        />
        <RailRadiusInfoWindow
          ref="railRadiusInfoWindowRef"
          :radius="radiusInfoWindow"
          @set-radius="setRadius"
          @close="handleCloseInfoWindow"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import circle_icon from '@/assets/images/map/circle_icon.png'
import rectangle_icon from '@/assets/images/map/rectangle_icon.png'
import polygon_icon from '@/assets/images/map/polygon_icon.png'

import { getRailList, addRail, deleteRail, editRail, updateRailStatus, getDistrictTree } from '@/api/mixing-station/mixingStation'
import type { Data as MixingPageData, RailListQuery, RailForm, RailRowData } from '@/api/mixing-station/mixingStation'
import type { Data as CustomerPageData } from '@/api/customer/customer'
import { ShapeTypeEnum } from './Enums.ts'
import { railTypeOptions, railStatusOptions } from '../options.ts'
import { wgs84ToGCJ02, gcj02ToWgs84 } from '@/utils/mapUtil.ts'
import { useFenceMap } from './useFenceMap.ts'

const props = defineProps<{
  /** 围栏所属业务[0-搅拌站围栏, 1-客户围栏] */
  businessType: 0 | 1
  rowData: MixingPageData & CustomerPageData
  modelValue: boolean
}>()

const emits = defineEmits(['update:modelValue', 'fetchData'])

const dialogVisible = computed({
  get() {
    return props.modelValue
  },
  set(val: boolean) {
    emits('update:modelValue', val)
  }
})

const tableData = ref<RailRowData[]>([])
const tableLoading = ref(false)
const sideOpened = ref(true)
const formRef = ref<FormInstance>()
const searchKey = ref('')
const submitLoading = ref(false)

const initFenceInfo: RailForm = {
  id: '',
  railType: 0, // 围栏类型
  address: '', // 围栏地址
  codes: '', // 围栏区域编码
  railData: [], //围栏区域数据
  lng: null, // 围栏中心点经度
  lat: null, // 围栏中心点纬度
  radius: null, //围栏半径
  shapeType: null //形状类型
}
const fenceInfo = reactive<RailForm>({ ...initFenceInfo })

const { map, AMap, initFenceMap, destroyMap, mouseTool, district, clearMarker, getAddress, calculateCenter } = useFenceMap()

const titleType = computed(() => (viewOrEditStatus.value === 0 ? '新增' : viewOrEditStatus.value === 1 ? '查看' : '编辑'))

// 打开弹框
const handleOpenDialog = async () => {
  await initFenceMap()
  createInfoWindowInstance()

  fetchRailList()
  getDistrictTreeFn()
}

// 初始化重置数据
function resetData() {
  formRef.value.resetFields()
  Object.assign(fenceInfo, { ...initFenceInfo })

  markerSearchValue.value = ''
  districtRailPolygon = []
  addDistrictRailData.value = []
  viewOrEditStatus.value = 0
}

const handleCloseDialog = () => {
  resetData()
  emits('fetchData')
  destroyMap()
}

// 获取围栏列表
const fetchRailList = () => {
  const { rowData, businessType } = props
  const data: RailListQuery = {
    belongToBusinessType: businessType,
    relationId: rowData.id,
    businessNumber: businessType === 0 ? rowData.number : rowData.customerCode,
    searchKeyword: searchKey.value
  }

  getRailList(data).then(res => {
    const result = res.result
    result.map(item => {
      const centerPoint = wgs84ToGCJ02(item.lng, item.lat)
      item.lng = centerPoint[0]
      item.lat = centerPoint[1]
    })
    tableData.value = result
    drawRailData()
  })
}

// ============= 搜索地址相关 start ===================
const markerSearchValue = ref('')
const markerRef = ref(null)

/** POI检索 */
// 地址搜索
function handleSearch(queryString, cb) {
  const placeSearch = new AMap.value.PlaceSearch({
    city: '',
    pageSize: 10, // 单页显示结果条数
    pageIndex: 1, // 页码
    citylimit: false // 是否强制限制在设置的城市内搜索
  })
  placeSearch.search(queryString, (status, result) => {
    if (result && typeof result === 'object' && result.poiList) {
      const list = result.poiList.pois
      list.forEach(item => {
        item.value = item.name
        item.label = item.name
      })
      cb(list)
    } else {
      cb([])
    }
  })
}
// 地址选择
function handleSelect(item) {
  clearMarker()

  const marker = new AMap.value.Marker({
    position: item.location,
    content: markerRef.value.$el,
    offset: new AMap.value.Pixel(-13, -30)
  })

  map.value.add(marker)
  map.value.setFitView(marker)
}
// ============= 设置标注点相关 end ===================

// ============= 自定义画围栏相关 start ===================
const railInfoWindowRef = ref(null)
const railRadiusInfoWindowRef = ref(null)
const currentOverlay = ref(null) // 当前查看的围栏
const viewOrEditStatus = ref(0) // 0 默认(其它) 1 查看 2 编辑
let overlayEditor = null
let infoWindowInstance = null // 地图弹框实例

const railInfo = ref<RailRowData>({}) // 围栏信息
const allowEdit = ref(false)
const radiusInfoWindow = ref<number>(0) // 编辑圆时半径

const addColorOption = {
  fillColor: '#00c1de',
  strokeColor: '#ea6b58'
}
const viewColorOption = {
  fillColor: '#ea6b58',
  strokeColor: '#ea6b58'
}
const editColorOption = {
  fillColor: '#3a75ff',
  strokeColor: '#ea6b58'
}

// 画围栏
function handleDraw(type) {
  if (fenceInfo.lng && fenceInfo.lat) {
    ElMessage.warning('请先提交没有保存的多边形围栏')
    return
  }
  mouseTool.value.close(true)

  switch (type) {
    case ShapeTypeEnum.Circle:
      mouseTool.value.circle(addColorOption)
      break
    case ShapeTypeEnum.Rectangle:
      mouseTool.value.rectangle(addColorOption)
      break
    case ShapeTypeEnum.Polygon: {
      mouseTool.value.polygon(addColorOption)
      break
    }
  }
  map.value.setDefaultCursor('crosshair')
  mouseTool.value.on('draw', function (e) {
    mouseTool.value.close()
    drawCallBack(e.obj)
  })
}
// 画完围栏回调
async function drawCallBack(overlay) {
  map.value.setDefaultCursor('pointer')
  let centerPosition: any
  if (overlay.className.indexOf('Circle') !== -1) {
    fenceInfo.radius = parseInt(overlay.getRadius())
    fenceInfo.shapeType = ShapeTypeEnum.Circle
    centerPosition = overlay.getCenter()
  } else if (overlay.className.indexOf('Rectangle') !== -1) {
    const bounds = overlay.getBounds()
    const southWest = bounds.getSouthWest()
    const northEast = bounds.getNorthEast()
    fenceInfo.shapeType = ShapeTypeEnum.Rectangle
    fenceInfo.railData = [
      [southWest.getLng(), southWest.getLat()],
      [northEast.getLng(), southWest.getLat()],
      [northEast.getLng(), northEast.getLat()],
      [southWest.getLng(), northEast.getLat()]
    ]
    centerPosition = overlay.getCenter()
  } else if (overlay.className.indexOf('Polygon') !== -1) {
    centerPosition = calculateCenter(overlay._opts.path)
    fenceInfo.shapeType = ShapeTypeEnum.Polygon
    fenceInfo.railData = overlay._opts.path
  }

  const addressInfo: Record<string, any> = await getAddress(centerPosition)
  fenceInfo.address = addressInfo.fullAddress

  fenceInfo.lng = centerPosition.getLng()
  fenceInfo.lat = centerPosition.getLat()
}

// 根据围栏列表回显地图围栏
function drawRailData() {
  currentOverlay.value = null
  const allOverlays = map.value.getAllOverlays()
  allOverlays.forEach(overlay => {
    const shapeType = overlay.getExtData()?.shapeType
    if (shapeType === ShapeTypeEnum.Circle || shapeType === ShapeTypeEnum.Rectangle || shapeType === ShapeTypeEnum.Polygon) {
      overlay.clearEvents('click')
      overlay.destroy()
    }
  })

  if (overlayEditor) overlayEditor.close()
  if (mouseTool.value) mouseTool.value.close(true)
  map.value.clearInfoWindow()
  const overlayArr = []
  tableData.value.forEach(item => {
    let overlay = null
    const option = {
      cursor: 'pointer',
      ...viewColorOption
    }
    if (item.shapeType === ShapeTypeEnum.Circle) {
      overlay = new AMap.value.Circle({
        center: [item.lng, item.lat],
        radius: item.radius, //半径
        ...option
      })
    } else if (item.shapeType === ShapeTypeEnum.Rectangle) {
      const railData = toGCJ02PointArr(JSON.parse(item.railData))
      const bounds = new AMap.value.Bounds(railData[0][0], railData[0][2])
      overlay = new AMap.value.Rectangle({
        bounds,
        ...option
      })
    } else if (item.shapeType === ShapeTypeEnum.Polygon) {
      let path = toGCJ02PointArr(JSON.parse(item.railData))
      if (item.railType === 1) {
        for (let i = 0; i < path.length; i++) {
          path[i] = [path[i]]
        }
      } else {
        path = path[0]
      }
      overlay = new AMap.value.Polygon({
        path,
        ...option
      })
    }
    if (overlay) {
      overlay.setExtData(item)
      overlayArr.push(overlay)
    }
  })

  overlayArr.forEach(overlay => {
    overlay.on('click', e => {
      const data = e.target.getExtData()
      const overlayEditorData = overlayEditor?.getTarget()?.getExtData()
      if (viewOrEditStatus.value === 2 && overlayEditorData?.shapeType === ShapeTypeEnum.Circle && overlayEditorData?.id === data?.id) {
        createRailRadiusWindowInfo()
      } else {
        handleViewOrEdit(data)
      }
    })
  })
  map.value.add(overlayArr)
  map.value.setFitView()
}

// 编辑围栏覆盖物
function editOverlay() {
  viewOrEditStatus.value = 2
  map.value.clearInfoWindow()
  let editorType = ''
  if (currentOverlay.value.className.indexOf('Circle') !== -1) {
    editorType = 'CircleEditor'
  } else if (currentOverlay.value.className.indexOf('Rectangle') !== -1) {
    editorType = 'RectangleEditor'
  } else if (currentOverlay.value.className.indexOf('Polygon') !== -1) {
    editorType = 'PolygonEditor'
  }
  overlayEditor = new AMap.value[editorType](map.value, currentOverlay.value)

  overlayEditor.open()
  currentOverlay.value.setOptions({
    ...editColorOption
  })
  overlayEditor.on('adjust', function (e) {
    console.log('触发事件：adjust')
    drawCallBack(e.target)
  })
  overlayEditor.on('move', function (e) {
    console.log('触发事件：move')
    drawCallBack(e.target)
  })
  overlayEditor.on('addnode', function (e) {
    console.log('触发事件：addnode')
    drawCallBack(e.target)
  })
}

// 生成地图弹框实例
function createInfoWindowInstance() {
  infoWindowInstance = new AMap.value.InfoWindow({
    isCustom: true, //使用自定义窗体
    autoMove: false,
    content: null,
    offset: new AMap.value.Pixel(0, -25)
  })
}

// 关闭地图弹框
function handleCloseInfoWindow() {
  if (infoWindowInstance) infoWindowInstance.close()
}

// 围栏信息弹框
function createRailWindowInfo(overlay, isAllowEdit = false) {
  infoWindowInstance.setContent(railInfoWindowRef.value.$el)

  railInfo.value = overlay.getExtData()
  allowEdit.value = isAllowEdit

  infoWindowInstance.open(map.value, new AMap.value.LngLat(railInfo.value.lng, railInfo.value.lat))
}

// 设置围栏半径弹窗
function createRailRadiusWindowInfo() {
  infoWindowInstance.setContent(railRadiusInfoWindowRef.value.$el)

  // 获取当前编辑圆的半径
  const circle = overlayEditor.getTarget()
  const center = circle.getCenter()

  radiusInfoWindow.value = circle.getRadius()
  infoWindowInstance.open(map.value, center)
}
// 编辑圆围栏时设置半径
function setRadius(radius: number) {
  if (!overlayEditor) return
  const circle = overlayEditor.getTarget()
  circle.setRadius(radius)
  drawCallBack(circle)
  currentOverlay.value = circle
  overlayEditor.close()
  editOverlay()
}

// 提交围栏
const handleAddRail = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      if (fenceInfo.railType === 1) {
        // 行政区域提交围栏
        addDistrictRail()
      } else {
        if (!fenceInfo.lat || !fenceInfo.lng) {
          ElMessage.warning('围栏数据为空，请在地图新建围栏!')
          return
        }
        fenceInfo.railData = [fenceInfo.railData]
        fetchAddRail()
      }
    }
  })
}
function fetchAddRail() {
  const { rowData, businessType } = props
  const data: RailForm = {
    ...fenceInfo,
    relationId: rowData.id,
    relationNumber: businessType === 0 ? rowData.number : rowData.customerCode,
    belongToBusinessType: businessType
  }
  const centerPoint = gcj02ToWgs84(fenceInfo.lng, fenceInfo.lat)
  data.lng = centerPoint[0]
  data.lat = centerPoint[1]
  const railData = JSON.stringify(toWgs84PointArr(fenceInfo.railData))
  const fetchFn = fenceInfo.id ? editRail : addRail

  submitLoading.value = true
  fetchFn({ ...data, railData })
    .then(() => {
      if (fenceInfo.railType === 1) clearDistrictRail()
      resetRailData()
      fetchRailList()
    })
    .finally(() => (submitLoading.value = false))
}

// 取消围栏
const handleCancelRail = () => {
  if (fenceInfo.railType === 1) {
    clearDistrictRail()
  }
  if (viewOrEditStatus.value === 2) {
    drawRailData()
  }
  resetRailData()
  mouseTool.value.close(true)
}

// 重置围栏数据
function resetRailData() {
  // formRef.value.resetFields()
  formRef.value.resetFields('address')
  formRef.value.resetFields('codes')
  Object.assign(fenceInfo, { ...initFenceInfo }, { railType: fenceInfo.railType })
  viewOrEditStatus.value = 0
}
// 查看编辑围栏
const handleViewOrEdit = row => {
  const overlayEditorData = overlayEditor?.getTarget()?.getExtData()
  if (viewOrEditStatus.value === 2) {
    if (row.id !== overlayEditorData.id) {
      ElMessage.warning('请先提交没有保存的多边形围栏!')
    }
    return
  }
  viewOrEditStatus.value = 1
  Object.assign(fenceInfo, row)
  fenceInfo.codes = row.address
  fenceInfo.railData = JSON.parse(row.railData)
  const allOverlays = map.value.getAllOverlays()
  allOverlays.forEach(overlay => {
    const extData = overlay.getExtData()
    if (extData?.id === row.id) {
      map.value.setFitView(overlay)
      if (currentOverlay.value) currentOverlay.value.setOptions({ fillColor: '#ea6b58', strokeColor: '#ea6b58' })
      currentOverlay.value = overlay
      currentOverlay.value.setOptions({ fillColor: '#3a75ff', strokeColor: '#ea6b58' })
      createRailWindowInfo(overlay, true)
    }
  })
}

// 高亮当前行
const tableRowClassName = ({ row }) => {
  if (!currentOverlay.value) return
  const currentRow = currentOverlay.value?.getExtData()
  if (row.id === currentRow?.id) {
    return 'current-row'
  }
}
// 改变围栏类型
const handleChangeType = () => {
  if (fenceInfo.railType === 0) {
    clearDistrictRail()
    resetRailData()
  }
  handleCancelRail()
}
// 火星坐标系转大地坐标系
function toWgs84PointArr(dataArr: any[]) {
  const pointArr = []
  for (let i = 0; i < dataArr.length; i++) {
    const item = dataArr[i]
    const pointJuniorArr = []
    for (let j = 0; j < item.length; j++) {
      const ele = item[j]
      let centerPoint
      if (Array.isArray(ele)) {
        centerPoint = gcj02ToWgs84(ele[0], ele[1])
      } else {
        centerPoint = gcj02ToWgs84(ele.lng, ele.lat)
      }
      pointJuniorArr.push({ lng: centerPoint[0], lat: centerPoint[1] })
    }
    pointArr.push(pointJuniorArr)
  }
  return pointArr
}

// 大地坐标系转火星坐标系
function toGCJ02PointArr(dataArr: any[]) {
  const pointArr = []
  for (let i = 0; i < dataArr.length; i++) {
    const item = dataArr[i]
    const pointJuniorArr = []
    for (let j = 0; j < item.length; j++) {
      const ele = item[j]
      pointJuniorArr.push(wgs84ToGCJ02(ele.lng, ele.lat))
    }
    pointArr.push(pointJuniorArr)
  }
  return pointArr
}
// -----------更改围栏状态-------//
const handleRailUpdateStatus = (row: RailRowData) => {
  ElMessageBox.confirm(`您确定更改围栏状态?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    updateRailStatus(row.id).then(() => {
      ElMessage.success('状态更改成功')
      fetchRailList()
    })
  })
}

// 删除围栏
const handleDeleteRail = id => {
  ElMessageBox.confirm(`您确定要删除此数据?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteRail(id)
    ElMessage.success('删除成功')
    fetchRailList()
  })
}

// ============= 行政区域画围栏相关 start ===================
const cascaderRef = ref(null)
const addDistrictRailData = ref([]) // 存放选择区域围栏的数据
let districtRailPolygon = [] // 存放区域围栏的覆盖物

// 选择行政区域
const changeDistrictCode = async value => {
  if (districtRailPolygon.length > 0) {
    map.value.remove(districtRailPolygon)
    districtRailPolygon = []
    addDistrictRailData.value = []
  }
  if (value.length > 0) {
    for (let i = 0; i < value.length; i++) {
      const item = value[i]
      const code = item[item.length - 1]
      const polygon = await drawDistrictRail(code)
      districtRailPolygon.push(polygon)
    }
    map.value.add(districtRailPolygon)
    map.value.setFitView(districtRailPolygon)
  }
}
// 生成行政区域围栏覆盖物
function drawDistrictRail(code) {
  return new Promise((resolve, reject) => {
    district.value.search(code, (status, result) => {
      if (status === 'complete') {
        const district = result.districtList[0] || {}
        const bounds = district.boundaries || []
        const path = []
        //生成行政区划polygon
        for (let i = 0; i < bounds.length; i++) {
          path.push([bounds[i]])
        }
        addDistrictRailData.value.push(district)
        const option = {
          path,
          cursor: 'pointer',
          fillColor: '#ea6b58',
          strokeColor: '#ea6b58'
        }
        const polygon = new AMap.value.Polygon(option)
        resolve(polygon)
      } else if (status === 'no_data') {
        console.log('没有查询到边界区域')
        reject()
      } else {
        reject()
      }
    })
  })
}

// 行政区域提交围栏
function addDistrictRail() {
  const nodes = cascaderRef.value.getCheckedNodes()
  addDistrictRailData.value.forEach((item, i) => {
    fenceInfo.lng = item.center.lng
    fenceInfo.lat = item.center.lat
    fenceInfo.address = nodes[i].text.replaceAll(' / ', '')
    fenceInfo.railData = item.boundaries
    fenceInfo.shapeType = ShapeTypeEnum.Polygon
    fetchAddRail()
  })
}

// 清除行政区域围栏信息
function clearDistrictRail() {
  map.value.remove(districtRailPolygon)
  districtRailPolygon = []
  addDistrictRailData.value = []
}

// 行政区域树
const purchaseAreaTree = ref([])

const getDistrictTreeFn = async () => {
  const { result } = await getDistrictTree()
  purchaseAreaTree.value = result
}
</script>
<style lang="scss" scoped>
.dialog-container {
  height: 660px;
  border-radius: 4px;
  border: 1px solid var(--el-border-color);
}
.left {
  width: 430px;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  .location-btn {
    margin-left: 5px;
    width: 34px;
    color: var(--el-color-primary);
    border-color: #9dbaff;
    background-color: #ebf1ff;
    &:hover {
      color: #fff;
      border-color: var(--el-color-primary);
      background-color: var(--el-color-primary);
      outline: none;
    }
  }
  .isSelectPoint-btn {
    color: #fff;
    border-color: var(--el-color-primary);
    background-color: var(--el-color-primary);
    outline: none;
  }
  :deep(.el-tooltip__trigger) {
    z-index: 161;
  }
}
.fold-inner-left {
  width: 0;
  transition: width 0.28s;
  overflow: hidden;
  border-right: none;
}

.right {
  position: relative;
  .toolbar-container {
    width: 32px;
    background: #ffffff;
    border-radius: 4px;
    padding: 5px 5px;
    position: absolute;
    right: 15px;
    top: 40px;
    .toolbar-item {
      cursor: pointer;
      border-bottom: 1px solid #ededed;
      padding: 5px 0px;
      box-sizing: border-box;
      // &:hover {
      //   background: var(--el-color-primary)-hover;
      // }
    }
    .toolbar-item:nth-last-of-type(1) {
      border-bottom: none;
    }
    img {
      width: 22px;
      height: 22px;
      display: block;
    }
  }
  .hamburger-container {
    width: 26px;
    height: 70px;
    background: url(../../../assets/images/hamburger-bg.png) no-repeat;
    background-size: 100% 100%;
    cursor: pointer;
    line-height: 70px;
    text-align: center;
    box-sizing: border-box;
    margin-left: -6px;
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    .fold-inner {
      transform: rotate(0);
      transition: transform 0.25s ease-in;
      &-rotate {
        transform: rotate(180deg);
        transition: transform 0.25s ease-out;
      }
    }
  }
}

.portion {
  padding: 15px 10px;
  box-sizing: border-box;
}

.title {
  position: relative;
  padding-left: 12px;
  font-weight: 600;
  margin-bottom: 10px;
  &::before {
    content: '';
    width: 3px;
    height: 8px;
    position: absolute;
    top: 50%;
    left: 0;
    transform: translateY(-50%);
    background-color: var(--el-color-primary);
  }
}

#map-container {
  width: 100%;
  height: 100%;
}

:deep(.el-dialog__body) {
  padding: 10px 20px;
}

:deep(.el-divider) {
  margin: 0;
}
</style>
